package tools;

import lejos.util.TimerListener;

/**Slight modification of Lejos Timer
 * fixed Timer object, with some similar functionality to java.Swing.Timer.
 * Replaces the one in lejos because when that one was stopped the next call 
 * to timedOut() would happen anyway. Slight modification of Lejos Timer
 *@author Antoine Lennartz
 */
public class Timer2
{
    private TimerListener myListener;
    private Thread myThread;
    private int delay;
    private boolean running;
    private boolean stopped;

    /**
     * Create a Timer object. Every theDelay milliseconds
     * the el.timedOut() function is called. You may
     * change the delay with setDelay(int). You need
     * to call start() explicitly.
     */
    public Timer2(int theDelay, TimerListener el) {
		running = false;
		delay = theDelay;
		myListener = el;
		stopped = false;
	
		myThread = new Thread() {
			public void run() {
				while(true) {
				   if (running){
		             try{ Thread.sleep(delay);}catch(Exception e){}
				      if(running && !stopped) myListener.timedOut();
				      stopped=false;
				   } else {
				       yield();
				   }
				}
		    }	
		};
		
		myThread.setDaemon(true);
    }

    /**
     * access how man milliseconds between timedOut() messages.
     */
    public synchronized int getDelay() {
    	return delay;
    }
    /**
     * Change the delay between timedOut messages. Safe to call
     * while start()ed. Time in milli-seconds.
     */
    public synchronized void setDelay(int newDelay) {
    	delay = newDelay;
    }

    /**
     * Stops the timer. timedOut() messages are not sent.
     */
    public synchronized void stop() {
		running=false;
		stopped=true;
    }

    /**
     * Starts the timer, telling it to send timeOut() methods
     * to the TimerListener.
     */
    public synchronized void start() {
		running = true;
		if (!myThread.isAlive())
		  myThread.start();
	    }
	}
